// Service Worker for caching static resources
const CACHE_NAME = 'xyuser-system-v1';
const urlsToCache = [
    '/styles/optimized.css',
    '/js/api-cache.js',
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
    'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js',
    'https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css'
];

// Install event - cache resources
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log('Opened cache');
                return cache.addAll(urlsToCache);
            })
    );
    // 立即激活新SW，避免需要二次刷新
    self.skipWaiting();
});

// Fetch event - serve from cache when possible
self.addEventListener('fetch', event => {
    const url = new URL(event.request.url);
    const isAPIRequest = url.pathname.startsWith('/project-shares') ||
                         url.pathname.startsWith('/projects') ||
                         url.pathname.startsWith('/submissions') ||
                         url.pathname.startsWith('/api/project-shares') ||
                         url.pathname.startsWith('/api/projects') ||
                         url.pathname.startsWith('/api/submissions');

    if (isAPIRequest || event.request.method !== 'GET') {
        event.respondWith(fetch(event.request));
        return;
    }

    event.respondWith(
        caches.match(event.request)
            .then(response => {
                if (response) {
                    return response;
                }
                return fetch(event.request);
            })
    );
});

// Activate event - clean up old caches
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames.map(cacheName => {
                    if (cacheName !== CACHE_NAME) {
                        console.log('Deleting old cache:', cacheName);
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
    // 立即接管已打开页面
    self.clients.claim();
});